let { mysql, config } = require('../qcloud')
let http = require('axios')

// 存储步数信息接口
module.exports = async (ctx, next) => {
    let { openId, stepInfoList } = ((ctx.request || {}).body || {})
    try {
        let qryMaxtime = await mysql('cLog').column('cLog.cid').max('cLog.createtime as maxtime').innerJoin('cMemberInfo', 'cMemberInfo.cid', 'cLog.cid').where({ openid: openId })
        let list
        // 存储日期最新步数
        if (qryMaxtime.length > 0 && qryMaxtime[0].maxtime instanceof Date) {
            let maxtime = qryMaxtime[0].maxtime.getTime() / 1000
            list = stepInfoList.filter(item => {
                return item.timestamp >= maxtime
            })
        } else {
            list = stepInfoList
        }
        if (list.length > 1) {
            let qryMemberInfo = await mysql('cMemberInfo').select('cid', 'officeid', 'groupid').where({ openid: openId })
            if (qryMemberInfo.length > 0) {
                let { cid, officeid, groupid } = qryMemberInfo[0]
                list = list.map(item => {
                    return {
                        cid,
                        step: item.step,
                        officeid,
                        groupid,
                        createtime: new Date(item.timestamp * 1000).format('yyyy-MM-dd hh:mm:ss')
                    }
                })
                await mysql('cLog').where({
                    cid,
                    createtime: new Date(qryMaxtime[0].maxtime).format('yyyy-MM-dd hh:mm:ss')
                }).del()
                await mysql('cLog').insert(list)
            }
        } else if (list.length === 1) {
            let { cid, maxtime } = qryMaxtime[0]
            await mysql('cLog').where({
                cid,
                createtime: new Date(maxtime).format('yyyy-MM-dd hh:mm:ss')
            }).update({
                step: list[0].step
            })
        }
        // 保存并查询排名
        let ranksRes = await http({
            url: `${config.host}/weapp/getranks`,
            method: 'GET'
        })
        ctx.state.code = ranksRes.data.code
        ctx.state.data = ranksRes.data.data
    } catch (error) {
        ctx.state.data = error
        ctx.state.code = 409
    }
}
